//
//  VillageRuleManagerViewController.m
//  Cunli
//
//  Created by 湛亚 on 16/1/4.
//  Copyright (c) 2016年 lilubin. All rights reserved.
//

#import "VillageRuleManagerViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Config.h"
#import "UIColor+Addition.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface VillageRuleManagerViewController ()<UITextViewDelegate>{
    
    UITextView *contentView;
    UILabel *placeHolderLabel;
}

@end

@implementation VillageRuleManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"村规民约发布";
    self.view.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
    
    [self getCurrentRule];
    [self createRuleTextView];
    [self addNavButton];
}

-(void)createRuleTextView{
    
    contentView=[[UITextView alloc]initWithFrame:CGRectMake(15, 10, kScreenWidth-30, kScreenHeight-80)];
    contentView.font=[UIFont systemFontOfSize:16];
    contentView.delegate=self;
    contentView.backgroundColor=[UIColor whiteColor];
    contentView.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    contentView.layer.borderWidth =1.0;
    contentView.backgroundColor=[UIColor whiteColor];
    contentView.layer.cornerRadius = 2.0;
    [self.view addSubview:contentView];
    
    //TextView占位符
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(3, 8, 150, 20)];
    placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
    placeHolderLabel.textColor = [UIColor convertHexColorToUIColor:0xbcbcc3];
    placeHolderLabel.backgroundColor = [UIColor clearColor];
    placeHolderLabel.alpha = 1;
    placeHolderLabel.text = @"撰写村规民约内容";
    placeHolderLabel.font=[UIFont systemFontOfSize:16];
    [contentView addSubview:placeHolderLabel];
    
    //增加监听，当键盘弹出改变contentView大小
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

-(void)addNavButton{
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 60, 30);
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30);
    [rightBtn addTarget:self action:@selector(publishRule) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

-(void)getCurrentRule{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"cgmy_detail.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"cgmy_detail"]) {
            
            NSDictionary *dic=[result objectForKey:@"data"];
            
            if ([dic isEqual:@""]) {
                
                return ;
            }
            
            if ([dic objectForKey:@"content"]) {
                
                NSString *string=[dic objectForKey:@"content"];
                NSString *str1=[string stringByReplacingOccurrencesOfString:@"<br/>" withString:@"\n"];
                NSString *str2=[str1 stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
                contentView.text=[self removeHTML:str2];
                placeHolderLabel.alpha=0;
            }
            
        }
        
    }failureAction:^{
        
    }];

}

#pragma mark - 发布村规民约

-(void)publishRule{
    
    if ([contentView.text isEqualToString:@""]) {
        [EMAlertView showAlertWithTitle:@"提示"
                                message:@"内容不能为空!"
                        completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
                            
                        } cancelButtonTitle:@"确定"
                      otherButtonTitles:nil,nil];
        return;
    }
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    [CheckParams setObject:contentView.text forKey:@"content"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"op_cgmypublish.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"op_cgmypublish"]) {
            
            [Config showHUDWithText:@"发布成功" andImage:@"done"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [Config showHUDWithText:@"发布失败" andImage:@"error"];
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"网络错误,发布失败" andImage:@"error"];
    }];
}

//输入框要编辑的时候
- (void)textChanged:(NSNotification *)notification
{
    if ([[contentView text] length] == 0) {
        placeHolderLabel.alpha=1;
    }
    else {
        placeHolderLabel.alpha=0;
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    contentView.frame=CGRectMake(15, 10, kScreenWidth-30, kScreenHeight-80);
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    contentView.frame=CGRectMake(15,10, kScreenWidth-30, kScreenHeight-80-keyboardRect.size.height);
    //NSLog(@"键盘位置%f",keyboardRect.size.height);
}

#pragma mark - 去除网页标签

- (NSString *)removeHTML:(NSString *)html{
    
    NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    
    NSMutableArray *componentsToKeep = [NSMutableArray array];
    
    for (int i = 0; i < [components count]; i = i + 2) {
        
        [componentsToKeep addObject:[components objectAtIndex:i]];
    }
    
    NSString *plainText = [componentsToKeep componentsJoinedByString:@""];
    
    return plainText;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
